package com.cloudbroker.bcs.platform.dav.middle.extservice.itn.token;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.common.constant.HttpConstant;
import com.cloudbroker.bcs.platform.dav.middle.extservice.itn.ITNField;
import com.cloudbroker.bcs.platform.dav.common.util.HttpUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ITNTokenFactory {
	private ITNToken token;
	private static ITNTokenFactory instance = new ITNTokenFactory();

	private ITNTokenFactory() {
	}

	public static ITNTokenFactory getInstance() {
		return instance;
	}

	public synchronized String getToken() {
		if (token == null || ValueUtil.getString(token.getAccess_token()).isEmpty() || token.expires()) {
			token = createNewToken();
		}
		return token.getAccess_token();
	}

	private ITNToken createNewToken() {
		String url = ConfigUtil.get("func.itn.login.url" , "https://open.hs.net/oauth2/oauth2/token");
		String redirect_uri = ConfigUtil.get("func.itn.login.redirect.url" , "http://192.168.60.34:8320/hbsc_operate/access_token.json");
		Map<String, Object> map = new HashMap<>();
		map.put("grant_type", "client_credentials");
		map.put("redirect_uri", redirect_uri);
		String tokenResult = HttpUtil.doPost(url, map,
				HttpConstant.CHARSET_UTF_8, HttpConstant.CHARSET_UTF_8,
				ITNField.BASIC);
		token = JSONObject.parseObject(tokenResult, ITNToken.class);
		token.setCreate_time(new Date());
		return token;
	}

}